package com.itheima.active;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/*
* 通知类，用于增强
*
* */
@Aspect
@Component
public class StuActive {


    @Autowired
    private RabbitTemplate rabbitTemplate;



    @Around("execution(* com.itheima.controller.*.*(..))")
    public Object beforeStu(ProceedingJoinPoint proceedingJoinPoint) {

        try {
            Map<String,Object> map=new HashMap<String,Object>();
            //当前时间就为掉用时间
            Date date = new Date();
            long l1=System.currentTimeMillis();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currenTime = simpleDateFormat.format(date);
            System.out.println(currenTime);
            map.put("currenTime",currenTime);
            //获取方法名
            String name = proceedingJoinPoint.getSignature().getName();
            map.put("methodname",name);
            //获取访问路劲
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String requestURL = request.getRequestURL().toString();
            map.put("url",requestURL);
            //获取执行时间
            Object proceed = proceedingJoinPoint.proceed();
            long l2 = System.currentTimeMillis();
            long l3=l2-l1;
            map.put("consumingTime",l3);
            rabbitTemplate.convertAndSend("spring_queue",JSON.toJSONString(map));




            return proceed;

        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return "您的代码有误";
        }


    }



}
